package com.loyal.loyalerp.shiro.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.loyal.loyalerp.mapper.EmployeeMapper;
import com.loyal.loyalerp.model.Employee;
import com.loyal.loyalerp.model.GyUser;
import com.loyal.loyalerp.service.EmployeeService;

public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	EmployeeService employService;

	/*//**
	 * 授权用户权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 获取用户
		GyUser user = (GyUser) SecurityUtils.getSubject().getPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 获取用户角色
		Set<String> roleSet = new HashSet<String>();
		roleSet.add("100002");
		info.setRoles(roleSet);

		// 获取用户权限
		Set<String> permissionSet = new HashSet<String>();
		permissionSet.add("权限添加");
		permissionSet.add("权限删除");
		info.setStringPermissions(permissionSet);
		return info;
	}

	/**
	 * 验证用户身份
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String username = token.getUsername();
		try {
			List<GyUser> employee = employService.queryUserByUsercode(username);// 查询用户
			if (employee.size() == 0)
				throw new UnknownAccountException();
			else {
				SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee.get(0), employee.get(0).getPassword(), getName());
				SecurityUtils.getSubject().getSession().setAttribute("user", employee.get(0));

				return info;
			}
		} catch (NumberFormatException e) {
			throw new UnknownAccountException();
		}

	}

}
